<template>
    <view class="countdown_verify">
		<view class="verify_text" :style="{width:width+'px',height:height+'px',borderRadius:borderRadius+'px',backgroundColor:bgColor,borderColor:bgColor || borderColor,color:fontColor || borderColor}" :class="{'not_operational':isSendCode}" @click="sendCode">
		{{isSucceed?newSecond+`s${sendAfter}` : msgText}}
		</view>
    </view>
</template>
<script>
export default {
   data() {
      return {
		isSendCode:false,//等待状态
		isSucceed:false,	//发送成功
		msgText:'',	
		newSecond:null,	
		timer:null,	//定时器
		sendfront:null,	//发送前
		sendCenter:null,//发送中
		sendAfter:null,	//发送后
      }
   },
   props:{
	   width:{	//宽度
		   default:''
	   },
	   height:{	//高度
		   default:''
	   },
	   borderRadius:{	//圆角
		   default:0
	   },
	   second:{	//倒计时
		   type:Number,
		   default:60
	   },
	   bgColor:{	//背景颜色
		   type:String,
		   default:''
	   },
	   borderColor:{	//边框颜色
			type:String,
			default:''
	   },
	   fontColor:{	//文字颜色
		   type:String,
		   default:''
	   },
	   textMsg:{	//文本
		   type:Object,
		   default:function(){
			   return {
				   sendfront:'发送验证码',
				   sendCenter:'请稍候...',
				   sendAfter:'后获取'
			   }
		   }
	   },
	   start:{	//默认倒计时状态
		   type:Boolean,
		   default:false
	   }
   },
   created() {
		
   },
   methods:{
		sendCode(){	//发送验证码
			if(this.isSendCode) return
			this.isSendCode = true
			this.msgText = this.sendCenter
			this.$emit('sendCode',true)
		},
		sendSucceed(){	//发送成功
			this.isSucceed = true
			this.newSecond = this.second
			this.timer = setInterval(() => {
				this.newSecond--
				if(this.newSecond <= 0){
					this.stopTime()
				}
			},1000)
		},
		stopTime(){	//发送失败或停止
			clearInterval(this.timer)
			this.isSendCode = false
			this.isSucceed = false
			this.newSecond = this.second
			this.msgText = this.sendfront
		}
   },
   mounted() {
	   let {sendfront,sendCenter,sendAfter} = this.textMsg
	   this.sendfront = sendfront || '发送验证码'
	   this.sendCenter = sendCenter || '请稍候...'
	   this.sendAfter = sendAfter || '后获取'
	   this.msgText = this.sendfront
	   if(this.start){
		   this.sendCode()
	   }
   },
   destroyed() {
		this.stopTime()
   }
}
</script>
<style lang='scss' scoped>
.countdown_verify{
	display: flex;
	.verify_text{
		border: 1px solid #59a8ff;
		color: #59a8ff;
		font-size: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 80px;
		min-height: 26px;
		padding: 0 8px;
		&.not_operational{
			opacity: .5;
		}
	}
}
</style>